<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Consul服务实例管理</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f5f5f5;
            margin: 0;
            padding: 0;
        }
        
        .header {
            background-color: #007bff;
            color: white;
            padding: 15px 30px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .back-btn, .logout-btn {
            background-color: #dc3545;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
        }
        
        .back-btn {
            background-color: #6c757d;
        }
        
        .container {
            max-width: 1200px;
            margin: 20px auto;
            padding: 0 20px;
        }
        
        .panel {
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            padding: 20px;
            margin-bottom: 20px;
        }
        
        .panel-title {
            margin-top: 0;
            margin-bottom: 20px;
            color: #333;
            border-bottom: 1px solid #eee;
            padding-bottom: 10px;
        }
        
        .form-group {
            margin-bottom: 15px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 5px;
            color: #555;
        }
        
        .form-group input, .form-group textarea {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        
        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }
        
        .btn-primary {
            background-color: #007bff;
            color: white;
        }
        
        .btn-danger {
            background-color: #dc3545;
            color: white;
        }
        
        .btn-secondary {
            background-color: #6c757d;
            color: white;
        }
        
        .btn-primary:hover {
            background-color: #0069d9;
        }
        
        .btn-danger:hover {
            background-color: #c82333;
        }
        
        .btn-secondary:hover {
            background-color: #5a6268;
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        
        th, td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }
        
        th {
            background-color: #f8f9fa;
            font-weight: bold;
        }
        
        tr:hover {
            background-color: #f5f5f5;
        }
        
        .actions {
            display: flex;
            gap: 10px;
        }
        
        .error-message {
            color: #dc3545;
            margin-top: 15px;
            display: none;
        }
        
        .success-message {
            color: #28a745;
            margin-top: 15px;
            display: none;
        }
    </style>
</head>
<body>
    <div class="header">
        <h2 id="serviceNameTitle">服务实例管理</h2>
        <div>
            <button id="backBtn" class="back-btn">返回服务列表</button>
            <button id="logoutBtn" class="logout-btn">退出登录</button>
        </div>
    </div>
    
    <div class="container">
        <!-- 新增实例面板 -->
        <div class="panel">
            <h3 class="panel-title">新增实例</h3>
            <form id="addInstanceForm">
                <div class="form-group">
                    <label for="instanceId">实例ID</label>
                    <input type="text" id="instanceId" name="instanceId" required>
                </div>
                <div class="form-group">
                    <label for="instanceAddress">实例地址</label>
                    <input type="text" id="instanceAddress" name="instanceAddress" required>
                </div>
                <div class="form-group">
                    <label for="instancePort">实例端口</label>
                    <input type="number" id="instancePort" name="instancePort" required>
                </div>
                <div class="form-group">
                    <label for="instanceTags">实例标签（多个标签用逗号分隔）</label>
                    <input type="text" id="instanceTags" name="instanceTags">
                </div>
                <div class="form-group">
                    <label for="checkHTTP">健康检查HTTP地址（可选）</label>
                    <input type="text" id="checkHTTP" name="checkHTTP">
                </div>
                <div class="form-group">
                    <label for="checkInterval">健康检查间隔（可选，如10s）</label>
                    <input type="text" id="checkInterval" name="checkInterval">
                </div>
                <div class="form-group">
                    <label for="checkTimeout">健康检查超时（可选，如5s）</label>
                    <input type="text" id="checkTimeout" name="checkTimeout">
                </div>
                <button type="submit" class="btn btn-primary">添加实例</button>
                <div id="addInstanceError" class="error-message"></div>
                <div id="addInstanceSuccess" class="success-message"></div>
            </form>
        </div>
        
        <!-- 实例列表面板 -->
        <div class="panel">
            <h3 class="panel-title">实例列表</h3>
            <button id="refreshBtn" class="btn btn-primary">刷新</button>
            <table id="instancesTable">
                <thead>
                    <tr>
                        <th>ServiceID</th>
                        <th>ServiceTags</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="instancesList">
                    <!-- 实例列表将通过JavaScript动态填充 -->
                </tbody>
            </table>
            <div id="instancesError" class="error-message"></div>
        </div>
    </div>

    <script>
        // 检查是否有认证token
        const authToken = localStorage.getItem('authToken');
        if (!authToken) {
            window.location.href = '/static/index.html';
        }
        
        // 从URL参数获取服务名称
        const urlParams = new URLSearchParams(window.location.search);
        const serviceName = urlParams.get('service');
        
        if (!serviceName) {
            window.location.href = '/static/services.html';
        }
        
        document.getElementById('serviceNameTitle').textContent = `${serviceName} - 实例管理`;
        
        // 设置认证头
        const authHeaders = {
            'Authorization': `Bearer ${authToken}`,
            'Content-Type': 'application/json'
        };
        
        // 返回服务列表
        document.getElementById('backBtn').addEventListener('click', function() {
            window.location.href = '/static/services.html';
        });
        
        // 退出登录
        document.getElementById('logoutBtn').addEventListener('click', function() {
            localStorage.removeItem('authToken');
            window.location.href = '/static/index.html';
        });
        
        // 刷新按钮
        document.getElementById('refreshBtn').addEventListener('click', loadInstances);
        
        // 添加实例表单提交
        document.getElementById('addInstanceForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const instanceData = {
                id: document.getElementById('instanceId').value,
                name: serviceName, // 使用当前服务名称
                address: document.getElementById('instanceAddress').value,
                port: parseInt(document.getElementById('instancePort').value),
                tags: document.getElementById('instanceTags').value.split(',').filter(tag => tag.trim() !== ''),
                check: {
                    http: document.getElementById('checkHTTP').value || undefined,
                    interval: document.getElementById('checkInterval').value || undefined,
                    timeout: document.getElementById('checkTimeout').value || undefined
                }
            };
            
            // 如果没有健康检查配置，移除check字段
            if (!instanceData.check.http && !instanceData.check.interval && !instanceData.check.timeout) {
                delete instanceData.check;
            }
            
            fetch('/api/services', {
                method: 'POST',
                headers: authHeaders,
                body: JSON.stringify(instanceData)
            })
            .then(response => response.json())
            .then(data => {
                if (data.message) {
                    document.getElementById('addInstanceSuccess').textContent = data.message;
                    document.getElementById('addInstanceSuccess').style.display = 'block';
                    document.getElementById('addInstanceError').style.display = 'none';
                    
                    // 清空表单
                    document.getElementById('addInstanceForm').reset();
                    
                    // 重新加载实例列表
                    loadInstances();
                } else if (data.error) {
                    document.getElementById('addInstanceError').textContent = data.error;
                    document.getElementById('addInstanceError').style.display = 'block';
                    document.getElementById('addInstanceSuccess').style.display = 'none';
                }
            })
            .catch(error => {
                document.getElementById('addInstanceError').textContent = '添加实例失败，请稍后重试';
                document.getElementById('addInstanceError').style.display = 'block';
                document.getElementById('addInstanceSuccess').style.display = 'none';
            });
        });
        
        // 加载实例列表
        function loadInstances() {
            fetch(`/api/services/${encodeURIComponent(serviceName)}/instances`, {
                headers: authHeaders
            })
            .then(response => response.json())
            .then(instances => {
                const tbody = document.getElementById('instancesList');
                tbody.innerHTML = '';
                
                instances.forEach(instance => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td>${instance.ServiceID}</td>
                        <td>${instance.ServiceTags ? instance.ServiceTags.join(', ') : ''}</td>
                        <td class="actions">
                            <button class="btn btn-danger" onclick="deleteInstance('${instance.ServiceID}')">删除</button>
                        </td>
                    `;
                    tbody.appendChild(row);
                });
                
                document.getElementById('instancesError').style.display = 'none';
            })
            .catch(error => {
                document.getElementById('instancesError').textContent = '加载实例列表失败，请稍后重试';
                document.getElementById('instancesError').style.display = 'block';
            });
        }
        
        // 删除实例
        function deleteInstance(instanceId) {
            if (confirm('确定要删除这个实例吗？')) {
                fetch(`/api/services/${instanceId}`, {
                    method: 'DELETE',
                    headers: authHeaders
                })
                .then(response => response.json())
                .then(data => {
                    if (data.message) {
                        alert(data.message);
                        // 重新加载实例列表
                        loadInstances();
                    } else if (data.error) {
                        alert('删除实例失败：' + data.error);
                    }
                })
                .catch(error => {
                    alert('删除实例失败，请稍后重试');
                });
            }
        }
        
        // 页面加载时获取实例列表
        document.addEventListener('DOMContentLoaded', loadInstances);
    </script>
</body>
</html>